package com.kcnet.qk.service;

import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import com.kcnet.qk.app.AppContext;
import com.kcnet.qk.constant.Const;
import com.kcnet.qk.controller.addfriend.AddFriendAdoptCTR;
import com.kcnet.qk.controller.addfriend.AddFriendFriendCTR;
import com.kcnet.qk.controller.addfriend.AddFriendHomeCTR;
import com.kcnet.qk.controller.addfriend.AddFriendPhoneCTR;
import com.kcnet.qk.controller.addfriend.AddFriendRecommedCTR;
import com.kcnet.qk.controller.addfriend.AddSearchPhoneCTR;
import com.kcnet.qk.controller.dynamic.TemeLineSendAllFriendMsgCTR;
import com.kcnet.qk.controller.dynamic.TemeLineSendHomeCTR;
import com.kcnet.qk.controller.dynamic.TemeLineSendHomeTimeCTR;
import com.kcnet.qk.controller.dynamic.TimeLineSendImgAndTextCTR;
import com.kcnet.qk.controller.dynamic.TimeLineSendImgCTR;
import com.kcnet.qk.controller.dynamic.TimeLineSendTextCTR;
import com.kcnet.qk.controller.group.TeamAttsTeamCTR;
import com.kcnet.qk.controller.group.TeamFriendZanHomeCTR;
import com.kcnet.qk.controller.group.TeamRqFriendCTR;
import com.kcnet.qk.controller.group.TeamTeamMagCTR;
import com.kcnet.qk.controller.hdyh.HdFriendTimeLineZans;
import com.kcnet.qk.controller.hdyh.HdTimeLineZans;
import com.kcnet.qk.controller.hdyh.HdyhNotiyCTR;
import com.kcnet.qk.util.NodeUtil;
import com.kcnet.qk.util.PreferenceHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.util.List;

import cn.jesse.nativelogger.NLogger;


/**
 * Created by czc on 2017/6/13.
 */

public class AutoAddPeopleService extends AccessibilityService {

    private static final String TAG = "AutoAddPeopleService";
    public AccessibilityNodeInfo node = null;
    private int mType;
    private boolean isStop;
    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        AppContext.getInstance().setmService(this);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        //isStop = PreferenceHelper.getBoolean(Const.PREF_KEY_STOP_AUTO_FLAG, false);
        try{
            int type = mType;
            Log.i(TAG, "event=" + AccessibilityEvent.eventTypeToString(event.getEventType()) + "  className=" + event.getClassName()+" type:"+type+" statys:"+isStop);
            if(event.getPackageName().equals("com.facebook.katana")){
                if (isStop) {
                    switch (type) {
                        case Const.KEY_TEAM_TEAM_MAG://小组管理
                            TeamTeamMagCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_TEAM_ATTS_TEAM://关注主页
                            TeamAttsTeamCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_TEAM_RQ_FRIEND_TEAM://邀请好友进组
                            TeamRqFriendCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_TEAM_RQ_FRIEND_ZANS://邀请好友点赞
                            TeamFriendZanHomeCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_TIMELINE_SEND_IMG_TEXT://发布图文
                            TimeLineSendImgAndTextCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_TIMELINE_SEND_IMG://发布图片
                            TimeLineSendImgCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_TIMELINE_SEND_HOME://发送到主页
                            TemeLineSendHomeCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_TIMELINE_SEND_HOME_TIME://发送主页到好友的时间线
                            TemeLineSendHomeTimeCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_TIMELINE_SEND_TEXT://发送文本
                            TimeLineSendTextCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_TIMELINE_SEND_ALL_MSG://发送全部好友消息
                            TemeLineSendAllFriendMsgCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_ADD_FIREND_PHONE://添加好友通讯录
                            AddFriendPhoneCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_ADD_FIREND_FRIED://天假好友的好友
                            AddFriendFriendCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_ADD_FIREND_RECOMMED://添加推荐好友
                            AddFriendRecommedCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_ADD_FIREND_ADOPT://确认哈有请求
                            AddFriendAdoptCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_ADD_FIREND_HOME://添加主页好友
                            AddFriendHomeCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_ADD_FRIEND_SEATCH_NAME://搜索好友
                            AddSearchPhoneCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_ADD_FRIEND_SEATCH_EMAIL://搜索好友
                            AddSearchPhoneCTR.getInstance().doTask(event);
                            break;
                        case Const.KEY_HDYH_TIMELINE://时间线点赞
                            HdTimeLineZans.getInstance().doTask(event);
                            break;
                        case Const.KEY_HDYH_TIMELINE_FRIEND://好友时间线点赞
                            HdFriendTimeLineZans.getInstance().doTask(event);
                            break;
                        case Const.KEY_HDYH_yh://养号功能
                            HdyhNotiyCTR.getInstance().doTask(event);
                            break;
                    }

                }
            }else {
                if (isStop) {
                    if(type == Const.KEY_TIMELINE_SEND_ALL_MSG){
                        //执行发送用户信息
                        TemeLineSendAllFriendMsgCTR.getInstance().doTask(event);
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }


    public AccessibilityNodeInfo getRoot() {
        return getRootInActiveWindow();
    }

    @Override
    public void onInterrupt() {
        Log.e(TAG, "onInterrupt");
//        if (mController != null) {
//          //  mController.saveRecord();
//        }
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
//        if (mController != null) {
//          //  mController.saveRecord();
//        }
        EventBus.getDefault().unregister(this);
        getRootInActiveWindow().recycle();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeController(Integer type) {
        NLogger.i(TAG, "changeController"+type);
        mType = type;

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void isOpen(Boolean flag) {
        NLogger.i(TAG, "isOpen changeController"+flag);
        isStop = flag;
    }


    /**
     * 全局返回事件
     */
    public void performBackClick() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        performGlobalAction(GLOBAL_ACTION_HOME);
    }

    /**
     * 返回上一级
     */
    public void BackClick() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        performGlobalAction(GLOBAL_ACTION_BACK);
    }

    /**
     * 滑动左到右
     */
    public void SWIPE_LEFT_AND_RIGHTClick() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        performGlobalAction(GESTURE_SWIPE_RIGHT);
    }

    /**
     * 滑动左到右
     */
    public void SWIPE_RIGHT_AND_LEFTClick() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        performGlobalAction(GESTURE_SWIPE_LEFT);
    }


    /**
     * 滑动下到上
     */
    public void SWIPE_DOWN_AND_UPClick() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        performGlobalAction(GESTURE_SWIPE_UP);
    }



    /**
     * 模拟物理点击方法
     *
     * @param cmd
     */
    public static void execShellCmd(String cmd) {
        try {
            // 申请获取root权限，这一步很重要，不然会没有作用
            Process process = Runtime.getRuntime().exec("su");
            // 获取输出流
            OutputStream outputStream = process.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeBytes(cmd);
            dataOutputStream.flush();
            dataOutputStream.close();
            outputStream.close();

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }


    /**
     * 复制方法
     *
     * @param string
     */
    public void copyToBoard(String string) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("text", string);
        cm.setPrimaryClip(clipData);
    }


    //自动输入打招呼内容
    public void inputHello(String hello) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        //找到当前获取焦点的view
        AccessibilityNodeInfo target = nodeInfo.findFocus(AccessibilityNodeInfo.FOCUS_INPUT);
        if (target == null) {
            Log.d(TAG, "inputHello: null");
            return;
        }
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("label", hello);
        clipboard.setPrimaryClip(clip);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            target.performAction(AccessibilityNodeInfo.ACTION_PASTE);
        }
    }

    /**
     * 粘贴
     *
     * @param id
     * @param i
     */
    public void paste(String id, int i) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        AccessibilityNodeInfo targetNode = null;
        node = null;
        try {
            if (node == null) {
                List<AccessibilityNodeInfo> list = nodeInfo
                        .findAccessibilityNodeInfosByViewId("com.tencent.mm:id/" + id);
                if (list.size() > 0)
                    node = list.get(i);
            }
            targetNode = node;
            if (targetNode != null) {
                targetNode.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                targetNode.performAction(AccessibilityNodeInfo.ACTION_PASTE);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    /**
     * 普通模式
     *
     * @param millis
     */
    public void normalMode(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
